package com.jerry.chat.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Component
public class NettyServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(NettyServer.class);

    private ServerBootstrap bootstrap = new ServerBootstrap();
    private NioEventLoopGroup boss = new NioEventLoopGroup();
    private NioEventLoopGroup worker = new NioEventLoopGroup();

    public void start() {
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WSChannelInitializer());

        var f = bootstrap.bind(12345);
        f.channel().closeFuture();
        LOGGER.info("Netty server started ...");
    }

    @PreDestroy
    public void close() {
        LOGGER.info("server closing...");
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }
}
